package com.digital.community.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtils {
	public boolean isFileExist(String path, String fileName)
	{
		File file = new File(path + fileName);
		return file.exists();
	}
	
	public void DeleteFile(String path, String fileName)
	{
		File file = new File(path + fileName);
		if(file.exists())
			file.delete();
	}
	
	public File createFile(String path, String fileName) throws IOException
	{
		File file = new File(path + fileName);
		file.createNewFile();
		return file;
	}
	
	public boolean FileReName(String path, String fileNameOld, String fileNameNew)
	{
		if(isFileExist(path, fileNameOld))
		{
			DeleteFile(path, fileNameNew);
			File fileOld = new File(path + fileNameOld);
			File fileNew = new File(path + fileNameNew);
			return fileOld.renameTo(fileNew);
		}
		
		return false;
	}
	
	public File Write2FileFromInput(String path, String fileName, InputStream input)
	{
		File file = null;
		OutputStream output = null;
		try{
			file = createFile(path, fileName);
			output = new FileOutputStream(file);
        	byte buffer [] = new byte[4 * 1024];
        	int length = 0;
        	while((length = input.read(buffer)) != -1)
        	{
        		System.out.println("length: " + length);
        		output.write(buffer,0,length);
        	}
        	output.flush();
		}
		catch(Exception e)
		{
			System.out.println(e);
			e.printStackTrace();
		}
		finally
		{
			try
			{
				output.close();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		return file;
	}
}
